package com.celesea.configuration.security;

import com.celesea.configuration.ehcache.EhcacheProvider;
import com.celesea.configuration.security.bean.AuthorityUser;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

import java.util.Map;

public class RedisUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

    private static Logger logger = LoggerFactory.getLogger(RedisUserDetailsService.class);

    private static final String LOGIN_SESSION_ID = "loginSessioinId";
    private static final String BRAND_ID = "brandId";
    private static final String SHOP_ID = "shopId";
    private static final String USER_ID = "userId";

    @Autowired
    private CasRedisProvider casRedisProvider;

    @Autowired
    private EhcacheProvider ehcacheProvider;

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
//        logger.info("cas token:{}", JSON.toJSONString(token));
        AttributePrincipal principal = token.getAssertion().getPrincipal();
        Map<String, Object> attrs = principal.getAttributes();

        String loginSessionId = (String) attrs.get(LOGIN_SESSION_ID);
//        logger.info("SSO认证成功:{}", JSON.toJSONString(attrs));

        AuthorityUser userDetails = ehcacheProvider.getUserDetailsFromCache(loginSessionId);
        if (userDetails == null) {
            userDetails = casRedisProvider.getUserInfoFromRedis(loginSessionId);
            Assert.notNull(userDetails,"获取用户登录信息失败："+loginSessionId);
            ehcacheProvider.cacheUserDetails(loginSessionId,userDetails);
            ehcacheProvider.cacheUserTimeStamp(loginSessionId);
//            logger.info("SSO登录信息->品牌信息：{}", userDetails.getSsoLoginInfo().getBrand());
//            logger.info("SSO登录信息->门店ID：{}", userDetails.getSsoLoginInfo().getCurrentShopId());
//            logger.info("SSO登录信息->门店名称：{}", userDetails.getSsoLoginInfo().getCurrentShopName());
//            logger.info("SSO登录信息->当前版本：{}", userDetails.getSsoLoginInfo().getCurrentVersion());
        }
        return userDetails;
    }
}
